import React, { useEffect, useMemo, useState } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload,  } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
//将图片文件读取成base64格式的地址
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('你只能上传 JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 1;
    if (!isLt2M) {
        message.error('你上传的图片要小于 1MB!');
    }
    return isJpgOrPng && isLt2M;
};

const MyUpload: React.FC<{ done: (response: any) => void, imageUrl: string, formInstance: any }> = (props) => {
    // console.log(props);
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>(props.imageUrl);
    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        //正在上传
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        //上传成功
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            // console.log(info)
            // message.success('上传成功')
            getBase64(info.file.originFileObj as RcFile, (url) => {
                setLoading(false);
                setImageUrl(url);
            });
            //回传的是图片上传成功后的结果
            props.done(info.file.response)
        }
        //上传出错
        if (info.file.status === 'error') {
            setLoading(false)
            // console.log('上传出错')
            message.error('上传出错')
        }
    };
    //获取form表单的数据
    useEffect(() => {
        let formData = props.formInstance.getFieldsValue();
        // console.log(formData); 
        setImageUrl(formData.imageUrl)
    }, [props.formInstance.getFieldsValue()])
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    return (
        <Upload
            name="img"
            method='post'
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="/api/upload/uploadImg"
            beforeUpload={beforeUpload}
            onChange={handleChange}
        >
            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
    );
};

export default MyUpload;